#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 2      // 输出型参数的个数
#define NUM 1024 // 缓冲区大小

using namespace std;

void Writer(int wfd)
{
  string s = "hello,world";
  pid_t self = getpid();
  int number = 0;
  char buffer[NUM]; // 缓冲区
  while (true)
  {
    buffer[0] = 0; // 字符串清空
    snprintf(buffer, sizeof(buffer), "%s-%d-%d", s.c_str(), self, number++);
    cout << buffer << endl;
    write(wfd, buffer, strlen(buffer));
    sleep(1);
  }
}

void Reader(int rfd)
{
  char buffer[NUM];
  while (true)
  {
    buffer[0] = 0;
    ssize_t n = read(rfd, buffer, sizeof(buffer));
    if (n > 0)
    {
      buffer[n] = 0; // 当成字符串
      cout << "father get a message[" << getpid() << "]#" << buffer << endl;
    }
    else if (n == 0)
    {
      cout << "father read file done!\n";
      break;
    }
    else
      break;
  }
}
int main()
{
  int pipefd[N] = {0};
  int n = pipe(pipefd); // 开出一个管道
  if (n < 0)
  {
    return 1;
  }
  // cout << "pipefd[0]:" << pipefd[0] << "pipefd[1]:" << pipefd[1] << endl;
  // 一个是管道的读端【0】，一个是管道的写端【1】
  // child->w   father-.r
  pid_t id = fork();
  if (id < 0)
    return 2;
  if (id == 0)
  {
    // child
    close(pipefd[0]);
    Writer(pipefd[1]);
    close(pipefd[1]);
    exit(0);
  }
  // father
  close(pipefd[1]);
  Reader(pipefd[0]);
  // 回收子进程
  pid_t rid = waitpid(id, nullptr, 0);
  if (rid < 0)
  {
    return 3;
  }
  close(pipefd[0]);
  return 0;
}